<script setup>
import {computed, ref} from "vue";
import {ICONS, OPERATE_DRAWER_MODE} from "@/common/constant.js";
import {add, detailById, modifyById} from "@/apis/sys/dict.js";
import {NButton, NInput, NSpace, useMessage} from "naive-ui";
import {renderIcon} from "@/utils/index.js";

const message = useMessage()
const formRef = ref(undefined)
const show = defineModel('show')
const props = defineProps({
  mode: {
    type: Number,
    default: OPERATE_DRAWER_MODE.DETAIL
  },
  id: {
    type: String,
    default: undefined
  }
})
const emits = defineEmits(['success'])
const showSubmitBtn = computed(() => {
  return props.mode === OPERATE_DRAWER_MODE.ADD || props.mode === OPERATE_DRAWER_MODE.EDIT
})
const disabled = computed(() => {
  return props.mode === OPERATE_DRAWER_MODE.DETAIL
})
const title = computed(() => {
  if (props.mode === OPERATE_DRAWER_MODE.ADD) {
    return '新增'
  } else if (props.mode === OPERATE_DRAWER_MODE.EDIT) {
    return '编辑'
  } else {
    return '详情'
  }
})
const rules = {
  name: [
    {required: true, message: '请输入字典名称', trigger: 'blur'}
  ],
  code: [
    {required: true, message: '请输入字典编码', trigger: 'blur'}
  ],
}
const initFormDataValue = {
  name: undefined,
  code: undefined,
  sysDictItemList: [],
}
const formData = ref({...initFormDataValue})
const onAfterEnter = () => {
  if (props.mode === OPERATE_DRAWER_MODE.DETAIL || props.mode === OPERATE_DRAWER_MODE.EDIT) {
    loadDetail(props.id)
  }
}
const onAfterLeave = () => {
  resetForm()
}
const resetForm = () => {
  formData.value = {...initFormDataValue}
}
const loadDetail = async (id) => {
  const {code, data} = await detailById(id)
  if (code === 0) {
    formData.value = data
    formData.value.checkedMenuIds = formData.value.menuIds
  }
}
const onFinish = () => {
  formRef.value.validate()
      .then(async () => {
        if (props.mode === OPERATE_DRAWER_MODE.ADD) {
          const {code} = await add(formData.value)
          if (code === 0) {
            message.success('新增成功')
            show.value = false
            emits('success')
          }
        } else if (props.mode === OPERATE_DRAWER_MODE.EDIT) {
          const {code} = await modifyById(props.id, formData.value)
          if (code === 0) {
            message.success('修改成功')
            show.value = false
            emits('success')
          }
        }
      })
}
const dictItemColumns = computed(() => {
  const baseColumns = [
    {
      title: '标签',
      key: 'label',
      render(row, index) {
        return h(NInput, {
          value: row.label,
          disabled: disabled.value,
          onUpdateValue: (value) => {
            row.label = value
          }
        });
      }
    },
    {
      title: '字典值',
      key: 'value',
      render(row, index) {
        return h(NInput, {
          value: row.value,
          disabled: disabled.value,
          onUpdateValue: (value) => {
            row.value = value
          }
        });
      }
    }
  ]
  if (!disabled.value) {
    baseColumns.push({
      title: '操作',
      render(row, index) {
        return h(NSpace, null, {
          default: () => [
            h(NButton, {
              type: 'error',
              size: 'small',
              strong: true,
              secondary: true,
              circle: true,
              onClick: () => {
                formData.value.sysDictItemList.splice(index, 1)
              }
            }, {icon: () => renderIcon(ICONS.MinusOutlined)})
          ]
        });
      }
    })
  }
  return baseColumns
})

</script>

<template>
  <n-drawer
      v-model:show="show"
      resizable
      :min-width="502"
      :default-width="502"
      @after-enter="onAfterEnter"
      @after-leave="onAfterLeave">
    <n-drawer-content
        :title="title"
        closable
        :native-scrollbar="false">
      <n-space vertical>
        <n-form ref="formRef"
                :model="formData"
                label-placement="left"
                label-width="80"
                :rules="rules">
          <n-form-item label="字典名称" path="name">
            <n-input v-model:value="formData.name" :disabled="disabled" placeholder="请输入"/>
          </n-form-item>
          <n-form-item label="字典编码" path="code">
            <n-input v-model:value="formData.code" :disabled="disabled" placeholder="请输入"/>
          </n-form-item>
        </n-form>
        <n-space justify="end" v-if="!disabled">
          <n-button round secondary type="primary"
                    @click="formData.sysDictItemList.push({label: undefined, value: undefined})">
            <template #icon>
              <component :is="ICONS.PlusOutlined"/>
            </template>
          </n-button>
        </n-space>
        <n-data-table
            remote
            ref="table"
            :columns="dictItemColumns"
            :data="formData.sysDictItemList || [{label: undefined, value: undefined}]"
            :row-key="(rowData) => rowData.id"/>
      </n-space>
      <template #footer>
        <n-space>
          <n-button type="primary" @click="onFinish" v-if="showSubmitBtn">提交</n-button>
          <n-button @click="show = false">取消</n-button>
        </n-space>
      </template>
    </n-drawer-content>
  </n-drawer>
</template>

<style scoped>

</style>